package j2bs;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/**
 *
 * @author Faraj
 */
public class J2BService extends Thread
{
    Socket clientControlSock, clientDataSock;
    BufferedReader ConReader;
    PrintWriter ConWriter;
    InputStream streamReader;
    OutputStream streamWriter;
    int requestType; // put - 0 , get - 1, del - 3
    int fileIndex;
    Long fileSize;
    String fileName;

    public J2BService(Socket cSock,Socket dSock) throws Exception {
        clientControlSock = cSock;
        clientDataSock = dSock;
        ConReader = new BufferedReader(new InputStreamReader(cSock.getInputStream()));
        ConWriter = new PrintWriter(cSock.getOutputStream(),true);
        streamReader = dSock.getInputStream();
        streamWriter = dSock.getOutputStream();

        String request = ConReader.readLine();

        if(request.substring(0,3).equalsIgnoreCase("put"))
        {
            requestType = 0;
            String[] dataArr = request.split(":");
            fileSize = Long.parseLong(dataArr[1]);
            fileName = dataArr[2];
        }
        else if(request.substring(0,3).equalsIgnoreCase("get"))
        {
            requestType = 1;
            try
            {
                String[] dataArr = request.split(":");
                fileIndex = Integer.parseInt(dataArr[1]);
            }
            catch(Exception ex)
            {
                requestType = -1;
            }
        }
        else if(request.substring(0,3).equalsIgnoreCase("del"))
        {
            requestType = 2;
            try
            {

                String[] dataArr = request.split(":");
                fileIndex = Integer.parseInt(dataArr[1]);
            }
            catch(Exception ex)
            {
                requestType = -1;
            }
        }
        start();
    }

    @Override
    public void run()
    {
        if(requestType == 0) // put
        {
            int newFileIndex = getMaxCountFile();
            try
            {
                File file = new File(J2BServer.storage,newFileIndex+"");

                while(!file.mkdir()) {
                    newFileIndex = getMaxCountFile();
                    file = new File(J2BServer.storage,newFileIndex+"");
                }

                file = new File(file,"/"+fileName);
                file.createNewFile();

                ConWriter.println(String.valueOf(newFileIndex));
                ConWriter.close();

                FileOutputStream fileOut = new FileOutputStream(file);

                byte[] dataArr = new byte[1024];
                long totalLen = 0;
                int tempLen = 0;
                int len = 1024;

                while ( totalLen < fileSize && tempLen >= 0)
                {
                    tempLen = streamReader.read(dataArr,0,len);
                    totalLen += tempLen;
                    fileOut.write(dataArr,0, tempLen);
                }
                streamReader.close();
                fileOut.close();
            }
            catch (IOException ex)
            {
                return;
            }
            finally
            {
                try {
                    clientControlSock.close();
                    clientDataSock.close();
                } catch (IOException ex) {
                    return;
                }
            }
        }
        else if(requestType == 1) // get
        {
            try
            {
                File file = new File(J2BServer.storage,fileIndex+"");

                file = file.listFiles()[0];

                ConWriter.println(file.getName()+":"+file.length());
                ConWriter.close();
                fileSize = file.length();
                FileInputStream fileIn = new FileInputStream(file);

                byte[] dataArr = new byte[1024];
                long totalLen = 0;
                int tempLen = 0;
                int len = 1024;

                while ( totalLen < fileSize && tempLen >= 0)
                {
                    tempLen = fileIn.read(dataArr,0,len);
                    totalLen += tempLen;
                    streamWriter.write(dataArr,0, tempLen);
                }
                streamWriter.close();
                fileIn.close();
            }
            catch (IOException ex)
            {
                return;
            }
            finally
            {
                try {
                    clientControlSock.close();
                    clientDataSock.close();
                } catch (IOException ex) {
                    return;
                }
            }
        }
        else if(requestType == 2) // del
        {
            try
            {
                File file = new File(J2BServer.storage,fileIndex+"");
                file = file.listFiles()[0];
                if(file.delete())
                    ConWriter.println(file.getName()+":"+file.length()+":true");
                else
                    ConWriter.println(file.getName()+":"+file.length()+":false");
                ConWriter.close();
            }
            catch(Exception ex)
            {
                return;
            }
            finally
            {
                try {
                    clientControlSock.close();
                    clientDataSock.close();
                } catch (IOException ex) {
                    return;
                }
            }
        }

    }

    private int getMaxCountFile()
    {
        File[] fileArr = J2BServer.storage.listFiles();
        int maxCount = 0;
        for (int i = 0; i < fileArr.length; i++)
        {
            File file = fileArr[i];
            String name = file.getName();
            int current = Integer.parseInt(name);
            if(maxCount < current)
                maxCount = current;
        }
        return maxCount+1;
    }

}
